package cn.haona.game.simb.wap.servlet.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import cn.haona.game.simb.object.bio.User;
import cn.haona.game.simb.servlet.Define;
import cn.haona.game.simb.servlet.SessionHn;

/**
 * Servlet Filter implementation class LoginFilter
 */
public class LoginFilter implements Filter
{

	/**
	 * Default constructor.
	 */
	public LoginFilter()
	{
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy()
	{
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException
	{

		// 登录、注册例外
		String uri = ((HttpServletRequest) request).getRequestURI();

		// 如果是例外的链接
		if ((uri.indexOf("loginValidate.action") != -1) || (uri.indexOf("userRegister.action") != -1)
				|| (uri.indexOf("registerShow.action") != -1))
		{
////			//截取后面的/xxx.action
//			int iIndex=uri.lastIndexOf("/");
//			String action=uri.substring(iIndex,uri.length());
////			//forward到xxx.action
//			request.getRequestDispatcher(action).forward(request, response);
			chain.doFilter(request, response);
		}
		//要过滤的链接
		else
		{

			boolean isLogined = false;
			// SessionHn
			SessionHn session = (SessionHn) request.getAttribute(Define.SESSION_ID);
			if (session != null)
			{
				// 取的User object
				User user = (User) session.getElement(SessionHn.KEY_USERBEAN);
				// 如果有user object
				if (user != null)
				{
					isLogined = true;
				}
			}

			if (isLogined)
			{
				chain.doFilter(request, response);
			}
			else
			{
//				chain.doFilter(request, response);
				request.getRequestDispatcher("/xhtml/login/login.jsp").forward(request, response);
			}
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException
	{

	}

}
